package com.service.business.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.service.core.exception.CommonException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QrCodeUtils {


    /**
     * 生成QR图片
     * IN：宽，高，图片格式，输出文件路径，内容
     * OUT：生成状态
     */
    public static void createQR(int width, int height, String format, String outPath, String content) {
        HashMap ha = new HashMap();
        ha.put(EncodeHintType.CHARACTER_SET, "utf-8");    //编码格式
        ha.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);    //纠错等级【L，M，Q，H】
        ha.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, ha);
            Path file = new File(outPath).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonException("生成二维码失败", "generate_qr_code_fail");
        }
    }

    /**
     * 解析QR码
     * IN：被解析图片路径
     * OUT：Map集合：
     * 		key：RESULT  》》  总结果集，未被解析
     * 			FORMAT  》》  被解析的二维码格式
     * 			TEXT  》》  二维码中含有的文本内容
     * 			STATE 》》 解析状态，成功或失败
     */
    public static Map analysisQR(String path) {
        Map resMap = new HashMap();        //返回出去的map集合
        try {
            MultiFormatReader formatReader = new MultiFormatReader();
            File file = new File(path);
            BufferedImage image = ImageIO.read(file);    //读取文件
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            HashMap hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 字符集
            Result result = formatReader.decode(binaryBitmap, hints);
            resMap.put("RESULT", result);    //总结果集
            resMap.put("FORMAT", result.getBarcodeFormat());    //被解析的二维码格式
            resMap.put("TEXT", result.getText());    //被解析的二维码含有的文本内容
            resMap.put("STATE", "SUCCESS");        //解析状态
        } catch (Exception e) {
            e.printStackTrace();
            resMap.put("STATE", "ERROR");
        }
        return resMap;
    }

}